<?php

namespace app\model;

use think\exception\ValidateException;
use think\Model;

use function GuzzleHttp\json_encode;

class Order extends Model
{

    protected $connection = 'mysql';

    protected $pk = 'id';

    protected $name = 'order';

    public function member()
    {
        return $this->hasOne(Member::class, 'id', 'uid');
    }
    public function orderRefund()
    {
        return $this->hasOne(OrderRefund::class, 'order_id');
    }

    public function orderGoods()
    {
        return $this->hasMany(OrderGoods::class, 'order_id');
    }

    public function paymethod()
    {
        return $this->hasOne(Paymethod::class, 'id', 'pay_method_id');
    }

    public function orderStatus()
    {
        return $this->hasOne(OrderStatus::class, 'id', 'order_status_id');
    }

    public function address()
    {
        return $this->hasOne(Address::class, 'id', 'address_id');
    }

    public function store()
    {
        return $this->hasOne(Store::class, 'id', 'sid');
    }

    public function technical()
    {
        return $this->hasOne(Technical::class, 'id', 'tid');
    }

    public function staff()
    {
        return $this->hasMany(OrderStaff::class, 'order_id', 'id');
    }

    public function staffOne()
    {
        return $this->hasOne(OrderStaff::class, 'order_id', 'id');
    }

    public function storeIncomelog()
    {
        return $this->hasOne(StoreIncomelog::class, 'order_id', 'id');
    }
    public function technicalIncomelog()
    {
        return $this->hasMany(TechnicalIncomelog::class, 'order_id', 'id');
    }

    /**
     * 写入订单
     * @param $payment_code 支付方式
     * @param $order_data 订单数据
     * return array
     */
    public function add_order($order_data = array())
    {
        $data = $this->get_order_data($order_data);

        $order['weid'] = weid();

        $order['sid'] = (int) $order_data['sid'];

        // $order['tid'] = json_encode($order_data['tid']);
        $order['tid'] = implode(',', $order_data['tid']);
        $order['beginTime'] = $order_data['beginTime'];
        $order['endTime'] = $order_data['endTime'];
        $order['toservicetime'] = $order_data['toservicetime'];
        $order['pay_method_id'] = (int) $order_data['pay_method_id'];
        $order['payment_code'] = $order_data['payment_code'];
        $order['points_order'] = (int) $order_data['is_PayPoints'];
        if ($order_data['distance']) {
            $order['distance'] = $order_data['distance'];
        }

        $order['tuan_id'] = (int) $order_data['tuanid'];
        $order['uid'] = (int) $data['uid'];
        $order['aid'] = '';
        $order['order_num_alias'] = $data['order_num_alias'];
        $order['name'] = $data['name'];
        $order['cat_id'] = $data['cat_id'];
        $order['ptype'] = (int) $data['ptype'];
        $order['is_additional'] = (int) $data['is_additional'];
        $order['deliverymode'] = (int) $data['deliverymode'];
        $order['address_id'] = (int) $data['address_id'];
        $order['peisongtype'] = $order_data['peisongtype'];

        $order['email'] = $data['email'];
        $order['tel'] = $data['tel'];

        $order['shipping_name'] = $data['shipping_name'];
        $order['shipping_province_name'] = $data['shipping_province_name'];
        $order['shipping_city_name'] =  $data['shipping_city_name'];
        $order['shipping_district_name'] =  $data['shipping_district_name'];

        $order['shipping_city_id'] = (int) $data['shipping_city_id'];
        $order['shipping_district_id'] = (int) $data['shipping_district_id'];
        $order['shipping_province_id'] = (int) $data['shipping_province_id'];
        $order['shipping_address'] = $data['shipping_address'];
        $order['shipping_tel'] = $data['shipping_tel'];
        $order['shipping_method'] = $data['shipping_method'];

        $order['is_express'] = 1;

        $order['remark'] = $data['remark'];
        $order['order_status_id'] = Config::getconfig()['default_order_status_id'];

        $order['ip'] = get_client_ip();
        $order['create_time'] = time();
        $order['update_time'] = time();
        $order['total'] = $data['total'];
        $order['total_settle'] = $data['total_settle'];
        $order['user_agent'] = $data['user_agent'];
        $order['pay_subject'] = isset($data['pay_subject']) ? $data['pay_subject'] : '';
        $order['return_points'] = isset($data['return_points']) ? $data['return_points'] : '';

        //积分抵扣
        if ($order_data['is_PayPoints'] == 1) {
            $order['pay_points'] = $data['pay_points'];
            $order['points_price'] = $data['points_price'];
            $order['total'] = round(($order['total'] - $order['points_price']), 2);
            if ($order['total'] == 0) {
                $order['payment_code'] = 'points_pay';
            }
        }

        //次卡设置
        $order['is_times'] = (int) $order_data['is_times'];
        if ($order['is_times'] == 1) {
            $order['timesmum'] = $data['goodss'][0]['timesmum'];
        }

        //跑腿订单设置
        $order['is_errands'] = (int) $data['is_errands'];

        if (empty($order['sid']) && !empty($data['goodss'][0]['sid'])) {
            $order['sid'] = $data['goodss'][0]['sid'];
        }

        if (!empty($order['tuan_id'])) {
            if (empty($order_data['jointuanid'])) {
                $order['tuan_found_id'] = TuanFound::add_found($order['tuan_id']);
            } else {
                $order['tuan_found_id'] = $order_data['jointuanid'];
            }
        }
        // return $order;
        $Orderdata = Order::create($order);
        $order_id = $Orderdata->id;

        if (!empty($order['tuan_id'])) {
            TuanFollow::add_follow([
                'order_id' => $order_id,
                'found_id' => $order['tuan_found_id'],
                'tuan_id' => $order['tuan_id'],
            ]);
        }

        if (isset($data['goodss'])) {
            //var_dump($data['goodss']);
            foreach ($data['goodss'] as $goods) {
                $goods_id = $goods['goods_id'];
                if (!empty($goods_id)) {
                    OrderGoods::create([
                        'order_id' => $order_id,
                        'goods_id' => $goods_id,
                        'name' => $goods['name'],
                        'model' => $goods['model'],
                        'image' => $goods['image'],
                        'sku' => $goods['sku'],
                        'quantity' => (int) $goods['quantity'],
                        'price' => (float) $goods['price'],
                        'total' => (float) $goods['total'],
                        'price_settle' => (float) $goods['price_settle'],
                        'total_settle' => (float) $goods['total_settle']
                    ]);
                }
            }
        }

        if (isset($data['totals'])) {
            foreach ($data['totals'] as $total) {
                OrderTotal::create([
                    'order_id' => $order_id,
                    'code' => $total['code'],
                    'title' => $total['title'],
                    'text' => $total['text'],
                    'value' => (float) $total['value']
                ]);
            }
        }

        $oh['order_id'] = $order_id;

        if (isset($data['pay_type']) && $data['pay_type'] == 'points') {
            $oh['order_status_id'] = Config::getconfig()['paid_order_status_id'];
        } else {
            $oh['order_status_id'] = Config::getconfig()['default_order_status_id'];
        }

        $oh['remark'] = $data['remark'];
        $oh['create_time'] = time();

        OrderHistory::create($oh);

        //上门服务/收件地址
        if ($order_data['address_id']) {
            $Address = [];
            $Address = Address::find($order_data['address_id']);
            if ($Address) {
                $Address = $Address->toArray();
                unset($Address['id']);
                $Address['order_id'] = $order_id;
                $Address['ptype'] = 1;
                OrderAddress::create($Address);
            }
        } else {
            if (!empty($order_data['shipping_province_name'])) {
                $Address = [];
                $Address['order_id'] = $order_id;
                $Address['ptype'] = 1;
                $Address['province_name'] = $order_data['shipping_province_name'];
                $Address['city_name'] = $order_data['shipping_city_name'];
                $Address['district_name'] = $order_data['shipping_district_name'];

                $Address['name'] = $order_data['shipping_name'];
                $Address['telephone'] = $order_data['shipping_tel'];
                $Address['address'] = $order_data['shipping_address'];

                $coder = Geocoder::geocoding($Address['province_name'] . $Address['city_name'] . $Address['district_name'] . $Address['address']);
                $Address['latitude'] = $coder['latitude'];
                $Address['longitude'] = $coder['longitude'];

                OrderAddress::create($Address);
            }
        }

        //跑腿取件地址
        if ($order_data['take_address_id']) {
            $take_address = [];
            $take_address = Address::find($order_data['take_address_id']);
            if ($take_address) {
                $take_address = $take_address->toArray();
                unset($take_address['id']);
                $take_address['order_id'] = $order_id;
                $take_address['ptype'] = 2;
                OrderAddress::create($take_address);
            }
        }

        //清空购物车
        if (!empty($order_data['cartid'])) {
            Cart::whereIn('id', $order_data['cartid'])->delete();
        }
        //积分支付
        if ($order_data['is_PayPoints'] == 1) {
            if ($order['total'] == 0) {
                $this->pay_order(['id' => $order_id]);
            }
        }

        return [
            'id' => $order_id,
            'order_id' => $order_id,
            'subject' => $order['pay_subject'],
            'name' => $order['shipping_name'], //收货人姓名
            'pay_order_no' => $order['order_num_alias'],
            'pay_total' => $order['total'],
            'payment_code' =>  $order['payment_code'],
            'uid' => (int) $order['uid']
        ];
    }

    //订单支付成功，订单历史，积分，商品数量
    public function pay_order($params)
    {
        $order_id = $params['id'];
        $pay_time = time();
        if (!empty($order_id) > 0) {
            $order_info = self::where(['id' => $order_id, 'order_status_id' => 1])->find();

            if (!empty($order_info)) {
                $order_info = $order_info->toArray();
                $common = Config::getconfig();

                if (!empty($params['payment_code'])) {
                    $order['payment_code'] =  $params['payment_code'];
                }

                $order['user_agent'] =  $params['user_agent'];

                $order['id'] = $order_id;

                if (OrderStaff::is_staff($order_id)) {
                    $order['order_status_id'] = 3;
                } else {
                    $order['order_status_id'] = $common['paid_order_status_id'];
                }



                $order['update_time'] = $pay_time;
                $order['pay_time'] = $pay_time;
                self::update($order);

                Member::where('id', $order_info['uid'])
                    ->inc('totleconsumed', $order_info['total'])
                    ->update();

                $cashlogsdata['uid'] = $order_info['uid'];
                $cashlogsdata['weid'] = weid();
                $cashlogsdata['order_id'] = $order_info['id'];
                $cashlogsdata['order_num_alias'] = $order_info['order_num_alias'];
                $cashlogsdata['remarks'] = '商品消费';
                $cashlogsdata['prefix'] = 2;
                $cashlogsdata['amount'] = $order_info['total'];
                $cashlogsdata['create_time'] = $pay_time;
                MemberCashlogs::create($cashlogsdata);

                $order_history['order_id'] = $order_id;
                $order_history['order_status_id'] = $common['paid_order_status_id'];
                $order_history['remark'] = '买家已付款';
                $order_history['create_time'] = $pay_time;
                $order_history['notify'] = 1;
                OrderHistory::create($order_history);

                //更新购买赠送的积分
                if (!empty($order_info['return_points'])) {
                    if ($order_info['return_points'] > 0) {
                        Points::create([
                            'weid' => weid(),
                            'uid' => $order_info['uid'],
                            'order_id' => $order_info['id'],
                            'order_num_alias' => $order_info['order_num_alias'],
                            'points' => $order_info['return_points'],
                            'description' => '下单积分',
                            'prefix' => 1,
                            'creat_time' => $pay_time,
                            'type' => 1
                        ]);

                        Member::where('id', $order_info['uid'])
                            ->inc('points', (int) $order_info['return_points'])
                            ->update();
                    }
                }
                //更新积分抵扣金额
                if ($order_info['points_order'] == 1) {
                    if ($order_info['pay_points'] > 0) {
                        Points::create([
                            'weid' => weid(),
                            'uid' => $order_info['uid'],
                            'order_id' => $order_info['id'],
                            'order_num_alias' => $order_info['order_num_alias'],
                            'points' => $order_info['pay_points'],
                            'description' => '下单抵扣' . $order_info['points_price'] . '元',
                            'prefix' => 2,
                            'creat_time' => $pay_time,
                            'type' => 1
                        ]);
                        Member::where('id', $order_info['uid'])
                            ->dec('points', (int) $order_info['pay_points'])
                            ->update();
                    }
                }

                //分销佣金处理
                $agent = Config::getconfig('agent');
                $share = Config::getconfig('share');
                if (!empty($agent['level'])) {
                    $level = $agent['level'];
                }
                if (!empty($agent['is_rebate'])) {
                    $is_rebate = $agent['is_rebate'];
                }

                //一层佣金

                if (!empty($level)) {
                    if ($level > 0) {
                        $firstpercent = $share['first'];
                        if (!empty($firstpercent)) {
                            $firstmember = Member::find($order_info['uid']);

                            if (!empty($firstmember)) {
                                $firstmember = $firstmember->toArray();
                                $firstmember['is_agent'] = Agent::is_agent($firstmember['id']);
                            }
                            if (!empty($is_rebate) && $firstmember['is_agent'] == 1) {
                                $firstuid = $order_info['uid'];
                            } else {

                                $firstuid = $firstmember['pid'];
                            }

                            Agent::setIncome($firstuid, $order_info, $firstpercent, 1);
                        }
                    }
                    //二层佣金
                    if ($level > 1 && !empty($firstuid)) {
                        $secondpercent = $share['second'];
                        if (!empty($secondpercent)) {
                            $secondmember = Member::find($firstuid);
                            if (!empty($secondmember)) {
                                $secondmember = $secondmember->toArray();
                            }
                            if ((int) $secondmember['pid'] > 0) {
                                Agent::setIncome($secondmember['pid'], $order_info, $secondpercent, 2);
                            }
                        }
                    }

                    //三层佣金
                    if ($level > 2 && !empty($secondmember['pid'])) {
                        $thirdpercent = $share['third'];
                        if (!empty($thirdpercent)) {
                            $thirdmember = Member::find($secondmember['pid']);
                            if (!empty($thirdmember)) {
                                $thirdmember = $thirdmember->toArray();
                            }
                            if ((int) $thirdmember['pid'] > 0) {
                                Agent::setIncome($thirdmember['pid'], $order_info, $thirdpercent, 3);
                            }
                        }
                    }
                }
                try {
                    $OrderGoods = OrderGoods::where(['order_id' => $order_id])
                        ->select()
                        ->toArray();

                    //更新商品数量和销量
                    foreach ($OrderGoods as $v) {
                        if ($v['goods_id']) {
                            Goods::where('id', $v['goods_id'])->dec('quantity', $v['quantity'])->update();
                            Goods::where('id', $v['goods_id'])->inc('sale_count')->update();
                        }
                    }
                } catch (\Exception $e) {
                    throw new ValidateException($e->getMessage());
                }

                //处理拼团
                if (!empty($order_info['tuan_found_id'])) {
                    TuanFound::where('id', $order_info['tuan_found_id'])->update(['pay_time' => $pay_time]);
                    TuanFollow::where(['order_id' => $order_info['id'], 'found_id' => $order_info['tuan_found_id']])->update(['pay_time' => $pay_time]);
                    TuanFound::where('id', $order_info['tuan_found_id'])->inc('join')->update();
                    TuanGoods::where('id', $order_info['tuan_id'])->inc('sale_count')->update();

                    $TuanFound =  TuanFound::where('id', $order_info['tuan_found_id'])->find();

                    if ((int) $TuanFound->join >= (int) $TuanFound->need) {
                        TuanFound::where(['id' => $order_info['tuan_found_id']])
                            ->update([
                                'tuan_end_time' => $pay_time,
                                'status' => 1,
                            ]);
                        TuanFollow::where(['found_id' => $order_info['tuan_found_id']])
                            ->update([
                                'tuan_end_time' => $pay_time,
                                'status' => 1,
                            ]);
                    }
                }

                $PrinterFeie =  new PrinterFeie();
                $PrinterFeie->printer(self::order_info($order_id));

                if (empty($order_info['sid'])) {
                    Message::undertake($order_info);
                }
                Message::orderPayNoticeAdmin($order_info);
                Message::sendMiniPaysuccess($order_info);
                Broadcast::neworder($order_info);
                OrderRemind::neworder($order_info);
            }
        }
    }
    //订单退款，处理订单历史，积分，商品数量
    static public function refund_order($postdata)
    {
        $paymentcode = $postdata['orderInfo']['payment_code'];
        $order_id = $postdata['OrderRefund']['order_id'];
        $refund_time = $postdata['OrderRefund']['response_time'];
        $r = true;

        if ($postdata['OrderRefund']['refund_status'] == 1) {
            if ($paymentcode == 'balance_pay' || $paymentcode == 'wechat_pay') {

                Member::where('id', $postdata['OrderRefund']['uid'])
                    ->inc('balance', $postdata['OrderRefund']['refund_price'])
                    ->update();

                $cashlogsdata['uid'] = $postdata['OrderRefund']['uid'];
                $cashlogsdata['weid'] = weid();
                $cashlogsdata['order_id'] = $order_id;
                $cashlogsdata['order_num_alias'] = $postdata['OrderRefund']['order_refund_no'];
                $cashlogsdata['remarks'] = '订单退款';
                $cashlogsdata['prefix'] = 1;
                $cashlogsdata['amount'] = $postdata['OrderRefund']['refund_price'];
                $cashlogsdata['create_time'] = $refund_time;
                MemberCashlogs::create($cashlogsdata);
            } elseif ($paymentcode == 'wx_pay') {
                if (!empty($postdata['orderInfo'])) {
                    $payment = Wxpay::make();
                    $total = round($postdata['orderInfo']['total'], 2);
                    $total = floatval($total * 100);

                    $refund_price = round($postdata['OrderRefund']['refund_price'], 2);
                    $refund_price = floatval($refund_price * 100);

                    $result = $payment->refund->byOutTradeNumber($postdata['orderInfo']['id'], $postdata['OrderRefund']['order_refund_no'], intval($total), intval($refund_price), [
                        // 可在此处传入其他参数，详细参数见微信支付文档
                        'refund_desc' => '订单退款',
                    ]);
                    if ($result['return_code'] === 'SUCCESS') { } else {
                        $r = false;
                    }
                }
            }

            if ($r) {
                Message::sendMiniRefundsuccess($postdata);
                $Points1 = Points::where(['order_id' => $order_id, 'prefix' => 1])->find();
                if (!empty($Points1)) {
                    $Points1 = $Points1->toArray();
                    $Points1['description'] = '订单退款，扣去赠送的积分';
                    $Points1['prefix'] = 2;
                    $Points1['creat_time'] = $refund_time;
                    unset($Points1['id']);
                    Points::create($Points1);
                    Member::where('id', $Points1['uid'])
                        ->dec('points', (int) $Points1['points'])
                        ->update();
                }

                $Points2 = Points::where(['order_id' => $order_id, 'prefix' => 2])->find();
                if (!empty($Points2)) {
                    $Points2 = $Points2->toArray();
                    $Points2['description'] = '订单退款，退还积分';
                    $Points2['prefix'] = 1;
                    $Points2['creat_time'] = $refund_time;
                    unset($Points2['id']);
                    Points::create($Points2);
                    Member::where('id', $Points2['uid'])
                        ->inc('points', (int) $Points2['points'])
                        ->update();
                }

                $Incomelog = Incomelog::where(['order_id' => $order_id, 'ptype' => 1])->select()->toArray();
                if (!empty($Incomelog)) {
                    foreach ($Incomelog as $agvo) {
                        if ($agvo) {
                            $agvo['description'] = '订单退款，扣除佣金';
                            $agvo['ptype'] = 2;
                            $agvo['creat_time'] = $refund_time;
                            $agvo['month_time'] = date('m', $refund_time);
                            $agvo['year_time'] = date('Y', $refund_time);
                            $agvo['order_status_id'] = 6;
                            unset($agvo['id']);
                            Incomelog::create($agvo);

                            Agent::where('uid', $agvo['uid'])->dec('income', $agvo['income'])->update();
                            Agent::where('uid', $agvo['uid'])->dec('total_income', $agvo['income'])->update();
                        }
                    }
                }

                $TechnicalIncomelog = TechnicalIncomelog::where(['order_id' => $order_id, 'ptype' => 1])->select()->toArray();
                if (!empty($TechnicalIncomelog)) {
                    $incomedata = [];
                    foreach ($TechnicalIncomelog as $incomedata) {
                        if ($incomedata) {

                            $incomedata['description'] = '订单退款，扣除佣金';
                            $incomedata['ptype'] = 2;
                            $incomedata['create_time'] = $refund_time;
                            $incomedata['month_time'] = date('m', $refund_time);
                            $incomedata['year_time'] = date('Y', time());
                            $incomedata['order_status_id'] = 6;
                            unset($incomedata['id']);
                            TechnicalIncomelog::create($incomedata);

                            Technical::where('uuid',  $incomedata['uuid'])->dec('income',  $incomedata['income'])->update();
                            Technical::where('uuid', $incomedata['uuid'])->dec('total_income', $incomedata['income'])->update();
                            Technical::where('uuid', $incomedata['uuid'])->dec('service_times', 1)->update();
                        }
                    }
                }

                $StoreIncomelog = StoreIncomelog::where(['order_id' => $order_id, 'ptype' => 1])->select()->toArray();
                if (!empty($StoreIncomelog)) {
                    $incomedata = [];
                    foreach ($StoreIncomelog as $incomedata) {
                        if ($incomedata) {

                            $incomedata['description'] = '订单退款，扣除佣金';
                            $incomedata['ptype'] = 2;
                            $incomedata['create_time'] = $refund_time;
                            $incomedata['month_time'] = date('m', $refund_time);
                            $incomedata['year_time'] = date('Y', time());
                            $incomedata['order_status_id'] = 6;
                            unset($incomedata['id']);
                            StoreIncomelog::create($incomedata);

                            Store::where('id', $incomedata['sid'])->dec('income', $incomedata['income'])->update();
                            Store::where('id', $incomedata['sid'])->dec('total_income', $incomedata['income'])->update();
                        }
                    }
                }

                $OperatingcityIncomelog = OperatingcityIncomelog::where(['order_id' => $order_id, 'ptype' => 1])->select()->toArray();
                if (!empty($OperatingcityIncomelog)) {
                    $incomedata = [];
                    foreach ($OperatingcityIncomelog as $incomedata) {
                        if ($incomedata) {
                            $incomedata['description'] = '订单退款，扣除佣金';
                            $incomedata['ptype'] = 2;
                            $incomedata['create_time'] = $refund_time;
                            $incomedata['month_time'] = date('m', $refund_time);
                            $incomedata['year_time'] = date('Y', time());
                            $incomedata['order_status_id'] = 6;
                            unset($incomedata['id']);
                            OperatingcityIncomelog::create($incomedata);

                            Operatingcity::where('id', $incomedata['ocid'])->dec('income', $incomedata['income'])->update();
                            Operatingcity::where('id', $incomedata['ocid'])->dec('total_income', $incomedata['income'])->update();
                        }
                    }
                }
            }
        }
        return $r;
    }

    static public function itional_pay($orderid)
    {
        self::where('id', $orderid)->update(['additional_pay_time' => time()]);
        $order_info = self::find($orderid);
        if ($order_info) {
            $order_info = $order_info->toArray();
            Message::itional_pay($order_info);
        }
    }

    private function get_order_data($param = array())
    {

        $address_id = (int) $param['address_id'];
        $technicalId = $param['technicalId'];
        $shipping_method = $param['shipping_method'];
        $remark = $param['remark'];

        if (isset($param['type'])) {
            $type = $param['type'];
            $data['pay_type'] = $param['type'];
        } else {
            $type = 'money';
        }

        //付款人        
        $Membermob = new Member;
        $payMember = $Membermob->getUserByWechat();

        $data['uid'] = $payMember['id'];
        $data['name'] = $payMember['username'];
        $data['email'] = $payMember['email'];
        $data['tel'] = $payMember['telephone'];

        //收货人 
        if (empty($address_id)) {
            $data['shipping_name'] = $param['shipping_name'];
            $data['shipping_tel'] = $param['shipping_tel'];

            $data['shipping_province_name'] = $param['shipping_province_name'];
            $data['shipping_city_name'] = $param['shipping_city_name'];
            $data['shipping_district_name'] = $param['shipping_district_name'];
            $data['shipping_address'] = $param['shipping_address'];
        } else {
            $shipping = Address::find($address_id);
            if (!empty($shipping)) {
                $shipping = $shipping->toArray();

                $shipping_city_id = empty($shipping['city_id']) ? '' : $shipping['city_id'];
                $data['shipping_name'] = empty($shipping['name']) ? '' : $shipping['name'];
                $data['shipping_tel'] = empty($shipping['telephone']) ? '' : $shipping['telephone'];

                $data['shipping_province_name'] = empty($shipping['province_name']) ? '' : $shipping['province_name'];
                $data['shipping_city_name'] = empty($shipping['city_name']) ? '' : $shipping['city_name'];
                $data['shipping_district_name'] = empty($shipping['district_name']) ? '' : $shipping['district_name'];

                $data['shipping_province_id'] = empty($shipping['province_id']) ? '' : $shipping['province_id'];
                $data['shipping_city_id'] = empty($shipping['city_id']) ? '' : $shipping['city_id'];
                $data['shipping_district_id'] = empty($shipping['district_id']) ? '' : $shipping['district_id'];
                $region_name = empty($shipping['region_name']) ? '' : $shipping['region_name'];
                $address = empty($shipping['address']) ? '' : $shipping['address'];
                $data['shipping_address'] = $region_name . $address;
            }
        }

        $data['shipping_method'] = empty($shipping_method) ? '' : $shipping_method;
        $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
        $data['create_time'] = time();

        $data['remark'] = empty($remark) ? '' : $remark;

        $subject = '';
        if (!empty($param['cat_id'])) {
            //用户发布需求订单
            $cat = Category::find($param['cat_id']);
            if (!empty($cat)) {
                $cat = $cat->toArray();
                $data['ptype'] = $cat['ptype'];
                $data['deliverymode'] = $cat['deliverymode'];
                $data['pay_subject'] = $cat['title'];
            }
            $data['is_additional'] = 1;
            $data['cat_id'] = $param['cat_id'];
            $data['total'] = $param['total'];
        } else if (!empty($param['take_address_id'])) {
            //跑腿订单
            $data['pay_subject'] = '跑腿订单';
            $data['is_errands'] = 1;
            $data['deliverymode'] = 1;
            $data['ptype'] = 2;
            $data['total'] = $param['total'];
        } else {

            $cart = new Cart;
            if (empty($param['cartid'])) {
                $cartdata[0]['goods_id'] = $param['goods_id'];
                $cartdata[0]['msid'] = $param['msid'];
                $cartdata[0]['tuanid'] = $param['tuanid'];
                $cartdata[0]['sku'] = $param['sku'];
                $cartdata[0]['quantity'] = $param['number'];

                $cartdata[0]['is_skumore'] = $param['is_skumore'];
                $cartdata[0]['skumore'] = $param['skumore'];

                $goodsarray = $cart->carttotal($cartdata);
            } else {
                $goodsarray = $cart->getlistbyid($param['cartid']);
            }

            $goodss = $goodsarray['shopList'];
            $weight = $goodsarray['weight'];
            $data['is_additional'] = $goodsarray['is_additional'];

            if ($goodss) {

                if ($goodss[0]['cat_id']) {
                    $cat = Category::find($goodss[0]['cat_id']);
                    if (!empty($cat)) {
                        $cat = $cat->toArray();
                    }
                    $data['deliverymode'] = $cat['deliverymode'];
                    $data['ptype'] = $cat['ptype'];
                }
                //上门路费
                if (!empty($technicalId)) {
                    $thefare = 0;
                    if (is_array($technicalId)) {
                        for ($i = 0; $i < count($technicalId); $i++) {
                            $thefare = $thefare + Address::getthefare($address_id, $technicalId[$i]);
                        }
                    } else {
                        $thefare = $thefare + Address::getthefare($address_id, $technicalId);
                    }
                }

                $test['shipping_method'] = $shipping_method;
                $test['weight'] = $weight;
                $test['shipping_city_id'] = $shipping_city_id;
                //运费
                $transport_fee = (new TransportExtend)->calc_transport($weight, $shipping_city_id);

                $t = 0;
                $s = 0;
                $pay_points = 0;
                $points_price = 0;
                $return_points = 0;

                foreach ($goodss as $goods) {
                    $t += $goods['total'];
                    $s += $goods['total_settle'];
                    $pay_points += $goods['totalPayPoints'];
                    $points_price += $goods['totalPointsPrice'];
                    $return_points += $goods['total_return_points'];

                    $goods_data[] = array(
                        'goods_id' => $goods['goods_id'],
                        'name' => $goods['name'],
                        'sid' => $goods['sid'],
                        'cat_id' => $goods['cat_id'],
                        'model' => $goods['model'],
                        'image' => $goods['image'],
                        'sku' => $goods['sku'],
                        'timesmum' => $goods['timesmum'],
                        'quantity' => $goods['quantity'],
                        'subtract' => $goods['subtract'],
                        'price' => $goods['price'],
                        'total' => $goods['total'],
                        'price_settle' => $goods['price_settle'],
                        'total_settle' => $goods['total_settle'],
                    );
                }

                //使用优惠券

                if (!empty($param['couponId'])) {

                    $coupon = CouponReceive::find($param['couponId']);
                    if (!empty($coupon)) {
                        $coupon = $coupon->toArray();
                    }

                    if ($coupon['coupon_type'] == 10) {
                        $t = $t - $coupon['reduce_price'];
                        $s = $s - $coupon['reduce_price'];
                    } elseif ($coupon['coupon_type'] == 20) {
                        $t = $t * ($coupon['discount'] / 10);
                        $s = $s * ($coupon['discount'] / 10);
                    }
                    CouponReceive::update(['is_use' => 1, 'id' => $param['couponId']]);
                }

                if (count($goodss) > 1) {
                    $subject = $goodss[0]['name'] . '等商品';
                } else {
                    $subject = $goodss[0]['name'];
                }
                $data['pay_subject'] = $subject;

                $data['total'] = ($t + $transport_fee['price'] + $thefare['thefare']);

                $data['total_settle'] = $s;

                $data['pay_points'] = $pay_points; //需要积分
                $data['points_price'] = $points_price; //抵扣金额
                $data['return_points'] = $return_points; //可得积分

                $data['totals'][0] = array(
                    'code' => 'sub_total',
                    'title' => '商品价格',
                    'text' => '￥' . $t,
                    'value' => $t
                );
                $data['totals'][1] = array(
                    'code' => 'shipping',
                    'title' => '运费',
                    'text' => '￥' . $transport_fee['price'],
                    'value' => $transport_fee['price']
                );

                $data['totals'][2] = array(
                    'code' => 'thefare',
                    'title' => '路费',
                    'text' => $thefare['distance'] . '公里，￥' . $thefare['thefare'],
                    'value' => $thefare['thefare']
                );
                $data['totals'][3] = array(
                    'code' => 'total',
                    'title' => '总价',
                    'text' => '￥' . ($t + $transport_fee['price'] + $thefare['thefare']),
                    'value' => ($t + $transport_fee['price'] + $thefare['thefare'])
                );

                $data['goodss'] = $goods_data;
            }
        }
        $data['order_num_alias'] = build_order_no();
        $data['pay_method_id'] = $param['pay_method_id'];
        return $data;
    }
    public static function statuscount($mod, $status)
    {
        return $mod->where('order_status_id', $status)->count();
    }

    //订单信息
    public static function order_info($id)
    {

        $order = self::where('id', $id)->with(['member', 'orderStatus', 'staff', 'store', 'technical', 'paymethod', 'address', 'storeIncomelog'])->find();

        if (!empty($order)) {
            $order->visible(['member' => ['id', 'uuid', 'nickname', 'userpic', 'telephone']]);
            $order = $order->toArray();
        }

        $OrderHistory = OrderHistory::where(['order_id' => $id])->order('id desc')->select()->toArray();

        if (!empty($OrderHistory)) {
            foreach ($OrderHistory as $result) {
                $histories[] = array(
                    'id' => $result['id'],
                    'image' => toimg($result['image']),
                    'status' => OrderStatus::get_order_status_name($result['order_status_id']),
                    'remark' => nl2br($result['remark']),
                    'create_time' => date('Y/m/d H:i:s', $result['create_time'])
                );
            }
        }

        if (!$order) {
            return false;
        }

        $order['shipping_province'] = $order['shipping_province_name'];
        $order['shipping_city'] = $order['shipping_city_name'];
        $order['shipping_district'] = $order['shipping_district_name'];
        $Area = new Area;
        if (!empty($order['shipping_province_id'])) {
            $order['shipping_province'] = $Area->get_area_name($order['shipping_province_id']);
        }
        if (!empty($order['shipping_city_id'])) {
            $order['shipping_city'] = $Area->get_area_name($order['shipping_city_id']);
        }
        if (!empty($order['shipping_district_id'])) {
            $order['shipping_district'] = $Area->get_area_name($order['shipping_district_id']);
        }

        $order_totalarray = OrderTotal::where(['order_id' => $id])->select()->toArray();

        foreach ($order_totalarray as $vo) {
            $order_total[$vo['code']] = $vo;
        }

        $OrderExpress = OrderExpress::where(['order_id' => $id])->find();
        if (!empty($OrderExpress)) {
            $OrderExpress = $OrderExpress->toArray();
        }

        if (!empty($OrderExpress['express_no'])) {
            $Kdniaoapimob = new Kdniaoapi;
            $logistics = $Kdniaoapimob->getOrderTracesByArray(['ShipperCode' => $OrderExpress['express_code'], 'LogisticCode' => $OrderExpress['express_no']]);
        }
        if (!empty($logistics['ShipperCode'])) {
            $logistics['expressname'] = Express::getExname($logistics['ShipperCode']);
        }

        if ($order['order_status_id'] == 6) {
            $OrderRefund = OrderRefund::where(['order_id' => $id])->find();
            if (!empty($OrderRefund)) {
                $OrderRefund = $OrderRefund->toArray();
            }

            if ($OrderRefund['refund_address_id']) {

                $RefundAddress = RefundAddress::find($OrderRefund['refund_address_id']);
                if (!empty($RefundAddress)) {
                    $RefundAddress = $RefundAddress->toArray();
                }

                if (!empty($RefundAddress)) {
                    $OrderRefund['re_name'] = $RefundAddress['name'];
                    $OrderRefund['re_mobile'] = $RefundAddress['mobile'];
                    $OrderRefund['re_address'] = $RefundAddress['address'];
                }
            }
        }

        $order['ServiceTime'] = time_format($order['beginTime']) . '-' . date('H:i', $order['endTime']);

        if ($order['is_times'] == 1) {

            if ($order['timesdate']) {
                if ($order['timestype'] == 1) {
                    $order['ServiceTime'] = '每月:' . $order['timesdate'] . '号';
                } else {
                    $order['ServiceTime'] = '每周周:' . $order['timesdate'];
                }
            } else {
                $order['ServiceTime'] = '还没有预约时间';
            }
        } else {
            $order['ServiceTime'] = time_format($order['beginTime']) . '-' . date('H:i', $order['endTime']);
        }

        $order['pay_time'] = time_format($order['pay_time']);
        $order['create_time'] = time_format($order['create_time']);

        $OrderImage =  OrderImage::where('order_id', $id)->field('image')->select()->toArray();

        if ($OrderImage) {
            foreach ($OrderImage  as $vo) {
                $order['OrderImage'][] = toimg($vo['image']);
            }
        }

        if (!empty($order['storeIncomelog'])) {
            $order['store']['incomelog'] = $order['storeIncomelog'];
            unset($order['storeIncomelog']);
        }
        if (!empty($order['store'])) {
            $order['store']['level_store'] = 5;
            $order['store']['level_store_specialty'] = 5;
            $order['store']['level_store_service'] = 5;
            $order['store'] = [$order['store']];
        }
        $staff = array();
        if (!empty($order['staff'])) {
            foreach ($order['staff'] as $key => $vo) {
                $staff[$key] = Technical::where(['uuid' => $vo['uuid']])->visible(['id', 'title', 'tel'])->find()->toArray();
                $staff[$key]['status'] = $vo['status'] ? '已完成' : '未完成';
                $staff[$key]['level_technical'] = 5;
                $staff[$key]['incomelog'] = TechnicalIncomelog::where(['order_id' => $id, 'uuid' => $vo['uuid']])->find();
            }
        }
        unset($order['staff']);
        $order['staff'] = $staff;
        $OrderGoods = new OrderGoods;
        return array(
            'orderInfo' => $order,
            'OrderRefund' => $OrderRefund,
            'goods' => $OrderGoods->getOrderGoods($id),
            'order_total' => $order_total,
            'logistics' => $logistics,
            'order_statuses' => OrderStatus::select()->toArray(),
            'histories' => $histories,
            'OrderExpress' => $OrderExpress,
        );
    }


    public static function setOrderList($orderList)
    {
        $OrderGoods = new OrderGoods;
        $errands = Config::getconfig('errands');
        foreach ($orderList as &$vo) {
            $vo['create_time'] = time_format($vo['create_time']);

            if ($vo['is_times'] == 1) {

                if ($vo['timesdate']) {
                    if ($vo['timestype'] == 1) {
                        $vo['timeslabel'] = '服务时间,每月:' . $vo['timesdate'] . '号';
                    } else {
                        $vo['timeslabel'] = '服务时间,每周周:' . $vo['timesdate'];
                    }
                } else {
                    $vo['timeslabel'] = '您还没有预约时间';
                }
            }

            if ($vo['is_errands'] == 1) {

                $vo['image'] = $errands['orderimage'];
            }

            $vo['points'] = $vo['pay_points'];
            if ($vo['ptype'] == '1') {
                $vo['statusStr'] = OrderStatus::get_order_status_name($vo['order_status_id']);
            } elseif ($vo['ptype'] == '2') {
                $vo['statusStr'] = OrderStatus::get_order_status_name_yuyue($vo['order_status_id']);
            }
            if (!empty($vo['cat_id'])) {
                $vo['cateMap']['image'] = Category::getImage($vo['cat_id']);
            } else {
                $vo['goodsMap'] = $OrderGoods->getOrderGoods($vo['id']);
            }
        }
        return $orderList;
    }
    public static function receiving($id)
    {
        $order['id'] = $id;
        $order['order_status_id'] = 3;
        self::update($order);
    }

    public static function complete($id)
    {
        $order['id'] = $id;
        $order['order_status_id'] = 5;
        $res = self::update($order);

        if (!empty($res)) {
            $order_info = self::find($id);
            if (!empty($order_info)) {
                $order_info = $order_info->toArray();
                Technical::setIncome($order_info);
                Store::setIncome($order_info);
                Operatingcity::setIncome($order_info);
                Message::sendMiniOrderComplete($order_info);
            }
        }

        return $order_info;
    }

    public static function completeStaff($id, $uuid)
    {
        if (empty($uuid)) {
            return false;
        }
        $where['order_id'] = $id;
        $where['uuid'] = $uuid;
        $res = OrderStaff::where($where)->update(['status' => 1]);

        // if (!empty($res)) {
        //     $order_info = self::find($id);
        //     if (!empty($order_info)) {
        //         $order_info = $order_info->toArray();
        //         Technical::setIncome($order_info);
        //         Store::setIncome($order_info);
        //         Operatingcity::setIncome($order_info);
        //         Message::sendMiniOrderComplete($order_info);
        //     }
        // }

        return OrderStaff::where($where)->find();
    }

    public static function cancel_order($id, $cancel_reason = '')
    {
        $order['id'] = $id;
        $order['order_status_id'] = Config::getconfig()['cancel_order_status_id'];
        $order['cancel_reason'] = $cancel_reason;
        $order['cancel_time'] = time();
        self::update($order);
    }

    //商家取消
    public static function cancel_stroe_order($id, $cancel_reason = '')
    {
        $order['id'] = $id;
        $order['order_status_id'] = Config::getconfig()['cancel_order_status_id'];
        $order['cancel_reason'] = $cancel_reason;
        $order['cancel_time'] = time();
        self::update($order);
    }

    public static function offline_order($id)
    {
        $order['id'] = $id;
        $order['is_offline_pay'] = 1;
        $order['offline_pay_time'] = time();
        self::update($order);
    }

    //加入订单历史
    public function add_order_history($id, $data = array())
    {

        $order['id'] = $id;
        $order['update_time'] = time();
        $order['order_status_id'] = $data['order_status_id'];
        self::update($order);

        $oh['order_id'] = $id;
        $oh['order_status_id'] = $data['order_status_id'];
        $oh['notify'] = (isset($data['notify']) ? (int) $data['notify'] : 0);
        $oh['remark'] = strip_tags($data['remark']);
        $oh['create_time'] = \strtotime($data['dateadd_ed']);
        $oh['image'] = $data['image'];
        $ohmod = OrderHistory::create($oh);

        return $ohmod->id;
    }

    //检查库存
    public static function getGoodsquantitiy($id)
    {

        $result = true;
        $list = OrderGoods::where(['order_id' => $id])->select()->toArray();

        for ($i = 0; $i < count($list); $i++) {

            $good_quantity = Goods::find($list[$i]['goods_id']);
            if (!empty($good_quantity)) {
                $good_quantity = $good_quantity->toArray();
            }

            if ($good_quantity['quantity'] < $list[$i]['quantity'] && $good_quantity['ptype'] != 2) {
                $result = false;
                continue;
            }
        }


        return $result;
    }
    //线下付款信息添加
    public function OfflinepaymentTap($id, $img, $remark)
    {
        global $_W;
        $offline['weid'] = weid();
        $offline['order_id'] = $id;
        $offline['image'] = $img;
        $offline['remark'] = $remark;
        $result = OrderOffline::create($offline);
        if ($result) {
            return true;
        } else
            return false;
    }

    public static function getoffline($id)
    {
        $list = OrderOffline::where(['order_id' => $id])->find();
        if (!empty($list)) {
            $list = $list->toArray();
        }

        $list['image'] =  toimg($list['image']);
        return $list;
    }
}
